package com.foxit.mongodb;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.google.code.morphia.Morphia;

public class MorphiaFactoryBean implements FactoryBean<Morphia>, InitializingBean, DisposableBean{
	/**
	 * 要扫描并映射的包
	 */
	private String[] mapPackages;  
	
	/**
	 * 要映射的类
	 */
	private String[] mapClasses;  
	
	public String[] getMapPackages() {
		return mapPackages;
	}

	public void setMapPackages(String[] mapPackages) {
		this.mapPackages = mapPackages;
	}

	public String[] getMapClasses() {
		return mapClasses;
	}

	public void setMapClasses(String[] mapClasses) {
		this.mapClasses = mapClasses;
	}

	public boolean isIgnoreInvalidClasses() {
		return ignoreInvalidClasses;
	}

	public void setIgnoreInvalidClasses(boolean ignoreInvalidClasses) {
		this.ignoreInvalidClasses = ignoreInvalidClasses;
	}

	public Morphia getMorphia() {
		return morphia;
	}

	public void setMorphia(Morphia morphia) {
		this.morphia = morphia;
	}

	/**
	 * 扫描包时，是否忽略不映射的类
	 * 这里按照Morphia的原始定义，默认设为false
	 */
	private boolean ignoreInvalidClasses = false;
	
	private Morphia morphia = null;
	
	public void destroy() throws Exception {
	}

	public void afterPropertiesSet() throws Exception {
		Morphia m = new Morphia();
		if (mapPackages != null) {
		   for (String packageName : mapPackages) {
			   m.mapPackage(packageName, ignoreInvalidClasses);
		   }
		}
		if (mapClasses != null) {  
		   for (String entityClass : mapClasses) {
		       m.map(Class.forName(entityClass));
		   }
		}
		this.morphia = m;
	}

	public Morphia getObject() throws Exception {
		return this.morphia;
	}

	public Class<?> getObjectType() {
		return Morphia.class;
	}

	public boolean isSingleton() {
		return true;
	}

}
